package com.yk.system.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yk.api.system.dto.TemplateDTO;
import com.yk.common.core.domain.BasePageQuery;
import com.yk.common.core.domain.PageResult;
import com.yk.common.core.domain.Result;
import com.yk.common.core.utils.LoginHelper;
import com.yk.common.log.annotation.Log;
import com.yk.common.log.constant.LogConstants;
import com.yk.common.log.enums.BusinessType;
import com.yk.system.entity.Device;
import com.yk.system.entity.Template;
import com.yk.system.service.DeviceService;
import com.yk.system.service.TemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 模型管理 yk-system
 *
 * @author lmx
 * @date 2023/10/16 18:15
 */
@Api(tags = "模型管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/vb/template")
public class TemplateController {

    private final TemplateService templateService;
    private final DeviceService deviceService;

    /**
     * 新增
     */
    @Log(title = "模型", businessType = BusinessType.INSERT)
    @ApiOperation("新增")
    @PostMapping("/add")
    public Result<Void> add(@Validated @RequestBody TemplateDTO dto) {
        try {
            templateService.add(dto);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.ok2Log(LogConstants.ADD + dto.getModelName());
    }

    /**
     * 编辑
     */
    @Log(title = "模型", businessType = BusinessType.UPDATE)
    @ApiOperation("编辑")
    @PostMapping("/edit")
    public Result<Void> edit(@Validated @RequestBody TemplateDTO dto) {
        try {
            Assert.notNull(dto.getId(), "参数错误");
            templateService.edit(dto);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.ok2Log(LogConstants.UPDATE + dto.getModelName());
    }

    /**
     * 删除
     */
    @Log(title = "模型", businessType = BusinessType.DELETE)
    @ApiOperation("删除")
    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody TemplateDTO dto) {
        Assert.notEmpty(dto.getTemplateIds(), "参数错误");
        long count = deviceService.count(Wrappers.lambdaQuery(Device.class).in(Device::getTemplateId, dto.getTemplateIds()));
        if (count > 0) {
            return Result.fail("该模型下有设备，不能删除");
        }
        List<Template> list = templateService.listByIds(dto.getTemplateIds());
        List<String> modelNameList = list.stream().map(Template::getModelName).collect(Collectors.toList());
        // 以、分割
        String modelNameStr = String.join("、", modelNameList);
        templateService.removeByIds(dto.getTemplateIds());
        templateService.removeCache(dto.getTemplateIds());
        return Result.ok2Log(LogConstants.DELETE + modelNameStr);
    }

    /**
     * 查看
     */
    @ApiOperation("查看")
    @GetMapping("/view/{id}")
    public Result<TemplateDTO> view(@PathVariable("id") Long id) {
        return Result.data(templateService.view(id));
    }

    /**
     * 全量查询
     */
    @ApiOperation("全量查询")
    @PostMapping("/list")
    public Result<List<Template>> list() {
        LambdaQueryWrapper<Template> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Template::getCreatedBy, LoginHelper.getLoginUserId());
        List<Template> list = templateService.list(lambda);
        return Result.data(list);
    }

    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @PostMapping("/page")
    public PageResult<TemplateDTO> page(@RequestBody BasePageQuery<TemplateDTO> pageParam) {
        pageParam.getParam().setCreatedBy(LoginHelper.getLoginUserId());
        IPage<TemplateDTO> page = templateService.queryPage(pageParam);
        return PageResult.success(page.getRecords(), page.getTotal());
    }
}
